//
//  PhotoBrowserViewController.swift
//  Weibo
//
//  Created by apple on 15/12/21.
//  Copyright © 2015年 idcast. All rights reserved.
//

import UIKit
import SVProgressHUD
/// 注册可重用cell的标示
private let PhotoBrowserViewCellId = "PhotoBrowserViewCellId"
///照片浏览器
class PhotoBrowserViewController: UIViewController {
    
    ///照片数组
    private var urls: [NSURL]
    ///当前选中的照片索引
    private var currentIndexPath: NSIndexPath
    ///监听方法
    //关闭
   @objc private func close() {
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    //保存
   @objc private func save() {
    //1 拿到图片
    let cell = collectionView.visibleCells()[0] as! PhotoBrowserCell
    //imageView 中可能因为网络没有图片 ---> 下载需要提示
    guard let image = cell.imageView.image else {
    
        return
    }
    
    //2 保存图片
    UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    
    }
    
    
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    
    @objc private func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?) {
    
        let message = (error == nil) ? "保存成功" : "保存失败"
        
        SVProgressHUD.showInfoWithStatus(message)
    }
    //MARK: 构造函数
    init(urls: [NSURL], indexPath: NSIndexPath) {
    
        self.urls = urls
        self.currentIndexPath = indexPath
        //调用父类的方法
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   // 相当于xib和sb 主要职责是创建视图层次结构 loadView 函数执行完毕 view上的元素要全部创建完成
    // 如果view == nil 系统会在调用view的getter 方法时 自动调用loadView 创建view
    override func loadView() {
        //1 设置跟试图
        var rect = UIScreen.mainScreen().bounds
        
        rect.size.width += 20
        
        view = UIView(frame: rect)
        
        //2 设置界面
        setupUI()
    }
   // 是视图加载完成被调用 loadView执行完毕被执行
    // 主要做数据加载 或者其他处理
    //但是： 目前市场上很多程序 没有实现 loadView 所有建立子控件的代码都在 viewDidLoad中
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //让 collectionView 滚动到指定位置
          collectionView.scrollToItemAtIndexPath(currentIndexPath, atScrollPosition: .CenteredHorizontally, animated: false)

//        print(urls)
//        print(currentIndexPath)
        
    }
    ///懒加载控件
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoBrowserViewLayout())
    ///关闭按钮
    private lazy var closeButton: UIButton = UIButton(title: "关闭",
        fontSize: 14,
        color: UIColor.whiteColor(),
        imageName: nil,
        backColor: UIColor.darkGrayColor())
    ///保存按钮
    private lazy var saveButton: UIButton = UIButton(title: "保存",
        fontSize: 14,
        color: UIColor.whiteColor(),
        imageName: nil,
        backColor: UIColor.darkGrayColor())
    //MARK: 自定义流水布局
    private class PhotoBrowserViewLayout: UICollectionViewFlowLayout {
    
        private override func prepareLayout() {
            super.prepareLayout()
            
            itemSize = collectionView!.bounds.size
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = .Horizontal
            
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
            
            collectionView?.showsHorizontalScrollIndicator = false
        }
    }
}
//MARK： 设置UI
private extension PhotoBrowserViewController {

    private func setupUI() {
    
        //1 添加控件
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        //2 设置布局
        collectionView.frame = view.bounds
        
        closeButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.left.equalTo(view.snp_left).offset(8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        
        saveButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.right.equalTo(view.snp_right).offset(-8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        //3 监听方法
        closeButton.addTarget(self, action: "close", forControlEvents: .TouchUpInside)
        saveButton.addTarget(self, action: "save", forControlEvents: .TouchUpInside)
        
        //4 准备控件
        prepareCollectionView()
    }
    //准备collectionView
    private func prepareCollectionView() {
    
        //1 注册可重用cell
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: PhotoBrowserViewCellId)
        //2 设置数据源
        collectionView.dataSource = self
    }
}

//MARK: 数据源方法
extension PhotoBrowserViewController: UICollectionViewDataSource {
  
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserViewCellId, forIndexPath: indexPath) as! PhotoBrowserCell

        cell.imageURL = urls[indexPath.item]
        //设置代理
        cell.photoDelegate = self
        return cell
    }
}
//MARK: PhotoBrowserCellDelegate
extension PhotoBrowserViewController: PhotoBrowserCellDelegate {

    func PhotoBrowserCellDidTapImage() {
        close()
    }
}